package com.food.user.controller;


import com.food.user.commos.Result;
import com.food.user.dto.UserAddressDto;
import com.food.user.entity.UserAddress;
import com.food.user.exception.MyParameterException;
import com.food.user.form.AddUserAddressForm;
import com.food.user.form.UpdateUserAddressForm;
import com.food.user.service.UserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 帅得一
 * @since 2023年06月17日
 */
@RestController
@RequestMapping("/userAddress")
@Api(tags = "用户地址接口")
public class UserAddressController {
    @Autowired
    private UserAddressService userAddressService;


    @PostMapping("/add")
    @ApiOperation("新增地址")
    public Result addUserAddress(@RequestBody @Valid AddUserAddressForm form, BindingResult br){
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        UserAddress userAddress =userAddressService.addUserAddress(form);
        return Result.success(200,"新增收货地址成功",userAddress);
    }

    @PostMapping("/update")
    @ApiOperation("修改地址")
    public Result updateUserAddress(@RequestBody @Valid UpdateUserAddressForm form, BindingResult br)throws  Exception{
        if (br.hasErrors()) {
            List<ObjectError> allErrors = br.getAllErrors();
            for (ObjectError allError : allErrors) {
                //获取打印提示信息
                System.out.println(allError.getDefaultMessage());
            }
            throw new MyParameterException(500, "参数校验失败");
        }
        UserAddress userAddress =userAddressService.updateUserAddress(form);
        return Result.success(200,"修改收货地址成功",userAddress);
    }

    @PostMapping("/del")
    @ApiOperation("删除地址")
    public Result delUserAddress(Long addressId) throws  Exception{
        userAddressService.delUserAddress(addressId);
        return Result.success(200,"删除该地址成功",null);
    }

    @GetMapping("/listAll")
    @ApiOperation("查询所有地址")
    public Result listAllAddress(){
        ArrayList<UserAddressDto> list=userAddressService.listAllAddress();
        return Result.success(200,"查询所有地址成功",list);
    }

}

